import cv2
import math
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 直方图均衡去雾方法

source = cv2.imread('Pic/source.jpg')
img = cv2.cvtColor(source, cv2.COLOR_RGB2YUV)  # YUV色彩空间是把亮度（Luma）与色度（Chroma）分离

img[:, :, 0] = cv2.equalizeHist(img[:, :, 0])
img_output = cv2.cvtColor(img, cv2.COLOR_YUV2RGB)

img_gray = cv2.cvtColor(source, cv2.COLOR_RGB2GRAY)
dst_gray = cv2.equalizeHist(img_gray)

hist, bins = np.histogram(img_gray.flatten(), 256, [0, 256])
cdf = hist.cumsum()
cdf_normalized = cdf * 256 / cdf.max()
plt.plot(cdf_normalized, color='b')
plt.xlabel('输入灰度级')  # 显示x轴名词，u是更改字符编码。
plt.ylabel(r'输出灰度级')
plt.title(r'直方图均衡化变换函数曲线')
plt.savefig('Pic/equalize_function.png', dpi=500)
plt.show()

# dst = cv2.resize(dst, (0, 0), fx=1.0, fy=1.0, interpolation=cv2.INTER_NEAREST)
cv2.imwrite('Pic/equalize_picture.jpg', img_output)
cv2.imshow('Source', source)
cv2.imshow('After', img_output)
cv2.waitKey(0)
cv2.destroyAllWindows()

plt.hist(img_gray.flatten(), range=(0, 255), bins=256, alpha=0.5, density=True)
plt.xlabel('s')  # 显示x轴名词，u是更改字符编码。
plt.ylabel(r'p(s)')
plt.title(r'直方图均衡化前图像直方图')
plt.savefig('Pic/equalize_Hist_before.png', dpi=500)
plt.show()

plt.hist(dst_gray.flatten(), range=(0, 255), bins=256, alpha=0.5, density=True)
plt.xlabel('s')  # 显示x轴名词，u是更改字符编码。
plt.ylabel(r'p(s)')
plt.title(r'直方图均衡化后图像直方图')
plt.savefig('Pic/equalize_Hist_after.png', dpi=500)
plt.show()
